package com.example.demo.controller;

import com.example.demo.common.AppValues;
import com.example.demo.common.MyResult;
import com.example.demo.common.PasswordUilt;
import com.example.demo.model.Userinfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录功能
     * @param request 请求
     * @param userinfo 前端传来的用户
     * @return
     */
    @RequestMapping("/login")
    public MyResult controllerLogin(HttpServletRequest request, Userinfo userinfo) {
        HttpSession session=request.getSession(true);
        //非空校验
        if(userinfo==null||userinfo.getUsername()==null||userinfo.getPassword()==null) {
            return MyResult.fail(-1,"密码或用户为空");
        }
        //用户密码比对
        Userinfo userinfo1=userService.login(userinfo);
        if(userinfo1==null) {
            return MyResult.fail(-1,"此用户未注册");
        }
        if(!PasswordUilt.decrypt(userinfo.getPassword(),userinfo1.getPassword())) {
            return MyResult.fail(-1,"密码错误");
        }
        //将session放入内存中,后期再加入Redis

        //将登录状态放入其中
        session.setAttribute(AppValues.USER_KEY,userinfo1);
        //到这里已经校验完毕,为了 保证密码隐秘性,要设置为空
        userinfo1.setPassword("");
        return MyResult.success(userinfo1);
    }

    /**
     * controller的注册校验
     * @param userinfo
     * @return
     */
    @RequestMapping("/reg")
    public MyResult controllerReg(Userinfo userinfo) {
        //非空校验
        if(userinfo==null||userinfo.getUsername()==null||userinfo.getPassword()==null||userinfo.getEmail()==null) {
            return MyResult.fail(404,"密码或用户或邮箱为空");
        }
        //密码加盐加密
        userinfo.setPassword(PasswordUilt.encryption(userinfo.getPassword()));
        return MyResult.success(userService.reg(userinfo));
    }

    /**
     * 匹配模块的用户信息返回
     * @param request 从session 中拿用户信息
     * @return
     */
    @RequestMapping("/getUser")
    public MyResult controllerGetUser(HttpServletRequest request) {
        HttpSession session =request.getSession(false);
        if(session==null||session.getAttribute(AppValues.USER_KEY)==null) {
            return MyResult.fail(-1,"用户未登录");
        }
        Userinfo userinfo= (Userinfo) session.getAttribute(AppValues.USER_KEY);//获取在session中存的用户信息
        return MyResult.success(userService.getUser(userinfo.getUserid()));
    }
}
